package sys

import (
	"xkginweb/global"
	sys2 "xkginweb/model/entity/sys"
	"xkginweb/model/vo"
)

type SysUserRolesService struct{}

// 用户授权
func (service *SysUserRolesService) SaveSysUserRoles(userId uint, sysUserRoles []*sys2.SysUserRoles) (err error) {
	tx := global.KSD_DB.Begin()
	// 删除用户对应的角色
	if err := tx.Where("user_id = ?", userId).Delete(&sys2.SysUserRoles{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 开始保存用户和角色的关系
	if err := tx.Create(sysUserRoles).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

// 查询用户授权的角色信息
func (service *SysUserRolesService) SelectUserRoles(userId uint) (sysRolesVo []*vo.SysRolesVo, err error) {
	err = global.KSD_DB.Select("t3.*").Table("sys_user_roles t1,sys_users t2,sys_roles t3").
		Where("t1.user_id = t2.id AND t3.id = t1.role_id AND t1.user_id = ?", userId).Scan(&sysRolesVo).Error
	return sysRolesVo, err
}
